package org.lq.ems.system.servlet;

import com.google.gson.Gson;
import org.lq.ems.system.service.DataDictionaryService;
import org.lq.ems.system.service.impl.DataDictionaryServiceImpl;
import org.lq.system.entity.DataDictionary;
import org.lq.util.CastUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 李冠良
 * @create 2020-10-18
 */
@WebServlet("/AjaxDataDictionary.do")
public class AjaxDataDictionary extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String method = request.getParameter("method");

        String id_str = request.getParameter("dataId");
        String dataContent = request.getParameter("dataContent");
        String dataType = request.getParameter("dataType");
        String dataDesc = request.getParameter("dataDesc");
        int data_id = CastUtil.castInt(id_str);

        DataDictionary dataDictionary = new DataDictionary();
        dataDictionary.setDataId(data_id);
        dataDictionary.setDataContent(dataContent);
        dataDictionary.setDataType(dataType);
        dataDictionary.setDataDesc(dataDesc);

        //Ajax分页需要的参数接收和转化
        String pageIndex_str = request.getParameter("page");
        String pageSize_str = request.getParameter("limit");
        int pageIndex = CastUtil.castInt(pageIndex_str);
        int paseSize = CastUtil.castInt(pageSize_str);

        int startIndex = (pageIndex - 1) * paseSize;

        DataDictionaryService dataDictionaryService = new DataDictionaryServiceImpl();
        PrintWriter out = response.getWriter();

        switch (method) {
            case "all":
                List<DataDictionary> list = dataDictionaryService.pageList(startIndex, paseSize);
                Gson gson = new Gson();
                out.print(gson.toJson(list));
                break;
            case "save":
                out.print(dataDictionaryService.save(dataDictionary) > 0);
                break;
            case "update":
                out.print(dataDictionaryService.update(dataDictionary) > 0);
                break;
            case "delete":
                out.print(dataDictionaryService.delete(data_id) > 0);
                break;
            case "type":
                out.print(new Gson().toJson(dataDictionaryService.getEducationalLevel()));
                break;
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


}
